package main

import (
	"fmt"
	"math/rand"
	"time"
)

// 做一个随机位生成器，程序可以提供无限的随机 0 或者 1 的序列：random_bitgen.go

func genbit(ch chan<- int, quit chan bool) {
	rand.Seed(int64(time.Now().Nanosecond()))
	for {
		select {
		case ch <- rand.Intn(2):
		case <-quit:
			return
		}
	}
}

func makeCostTime() func() int64 {
	ts := time.Now().UnixMicro()
	return func() int64 {
		t := time.Now().UnixMicro()
		ts, t = t, t-ts
		return t
	}
}

func main() {
	costTime := makeCostTime()

	n := 100
	ch := make(chan int)
	quit := make(chan bool)
	go genbit(ch, quit)
	for i := 0; i < n; i++ {
		fmt.Print(<-ch, " ")
	}
	quit <- true
	fmt.Println("")
	fmt.Println("Cost time: ", costTime(), "ms")

	ch2 := make(chan int)
	done := make(chan bool)
	go func() {
		for {
			select {
			case i := <-ch2:
				fmt.Print(i, " ")
			case <-done:
				return
			}
		}
	}()
	for i := 0; i < n; i++ {
		select {
		case ch2 <- 0:
		case ch2 <- 1:
		}
	}
	done <- true
	fmt.Println("")
	fmt.Println("Cost time: ", costTime(), "ms")

}
